package hk.m4s.lr.repair.test.ui.anount;

import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;

public class phoneNoTextWatcher implements TextWatcher {

	private EditText mPhoneNoEdt;
	private int beforeTextLength = 0;//改变之前的字串长度
	private int onTextLength = 0;////改变中的字串长度
	private boolean isChanged = false;//
	private int location = 0;// 记录光标的位置
	private OnTextChangedListener lister;
	
//	private char[] tempChar;
	private StringBuffer buffer = new StringBuffer();
	int konggeNumberB = 0;
	
	public phoneNoTextWatcher(EditText phoneNoEdt) {
		mPhoneNoEdt = phoneNoEdt;
		lister = null;
	}
	
	public phoneNoTextWatcher(EditText phoneNoEdt, OnTextChangedListener lister) {
		mPhoneNoEdt = phoneNoEdt;
		this.lister = lister;
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
								  int after) {
		// TODO Auto-generated method stub
		beforeTextLength = s.length();
		if (buffer.length() > 0) {
			buffer.delete(0, buffer.length());
		}
		konggeNumberB = 0;
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == ' ') {
				konggeNumberB++;
			}
		}
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		onTextLength = s.length();
		buffer.append(s.toString());

		if (onTextLength == beforeTextLength || onTextLength <= 2 || isChanged) {
			isChanged = false;
			return;
		}
		isChanged = true;
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		if (isChanged) {
			location = mPhoneNoEdt.getSelectionEnd();
			int index = 0;
			while (index < buffer.length()) {
				if (buffer.charAt(index) == ' ') {
					buffer.deleteCharAt(index);
				} else {
					index++;
				}
			}
			index = 0;
			int konggeNumberC = 0;
			while (index < buffer.length()) {
//				if ((index + 1) % 5 == 0) {
				if ((index == 3 || index == 8 || index == 13)) {
					buffer.insert(index, ' ');
					konggeNumberC++;
				}
				index++;
			}
			if (konggeNumberC > konggeNumberB) {
				location += (konggeNumberC - konggeNumberB);
			}
//			tempChar = new char[buffer.length()];
//			buffer.getChars(0, buffer.length(), tempChar, 0);
			String str = buffer.toString();
			if (location > str.length()) {
				location = str.length();
			} else if (location < 0) {
				location = 0;
			}
			mPhoneNoEdt.setText(str);
			Editable etable = mPhoneNoEdt.getText();
			Selection.setSelection(etable, location);
			isChanged = false;
		}
		if(lister != null)
		{
			lister.onTextCheck(s.toString());
		}
	}

}
